package com.wch.SpringBootTestDemo.aspect;

import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 在spring-boot中使用aop
 * 记录dao层执行情况
 * @author 19821
 *
 */
@Aspect
@Component
public class LogDaoAspect {
	
	private Logger logger = LoggerFactory.getLogger(LogDaoAspect.class);
	
	private Long startDate;
	private Long endDate;
	private Long countDate;
	
	@Pointcut("execution(public * com.wch.SpringBootTestDemo..*Dao*.*(..))")
	public void proExecute(){
		
	}
	
	@Before("proExecute()")
	public void doBefore(JoinPoint joinPoint){
		startDate = System.currentTimeMillis();
		logger.info("------------------------DAO#REQUEST----------------------");
		logger.info("STARTDATE : " + startDate);

		// 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
	}
	
	@AfterReturning(returning = "ret",pointcut = "proExecute()")
	public void doAfterReturning(Object ret){
		endDate = System.currentTimeMillis();
		countDate = endDate - startDate;
		// 处理完请求，返回内容
		logger.info("------------------------DAO#RESPONSE----------------------");
		logger.info("ENDDATE : " + endDate);
		logger.info("COUNTDATE : " + countDate);
        logger.info("RESPONSE : " + ret);
        
	}
	
	
}
